let swiperStyle = null;
let swiperTotalWidth = 0;
let currentIndex = 1;
let swiperItemCount = 0;
let swiperTimer = null;
let indecatorItems = [];

window.onload = () => {
  // 处理元素
  configSwiperItems();
  // 设置元素初始化位置
  setTransform(-swiperTotalWidth);
  indecatorItems[0].className = "indicator-item indicator-item-active";
  // 启动计时器，自动轮播
  startTimer();
}

let configSwiperItems = () => {
  // swiper
  let swiper = document.querySelector(".swiper");
  // item list 
  let swiperItems = swiper.getElementsByClassName("swiper-item");
  // item length
  swiperItemCount = swiperItems.length;

  // 复制第一个节点，包含其子元素
  let firstItem = swiperItems[0];
  let firstNode = firstItem.cloneNode(true);
  // 复制最后一个节点，包含其子元素
  let lastItem = swiperItems[swiperItemCount - 1];
  let lastNode = lastItem.cloneNode(true);
  // 在第一个item前,增加一个最后的item
  swiper.insertBefore(lastNode, firstItem);
  swiper.appendChild(firstNode);

  // 获取元素的宽度（出去伪元素后，所有内容的总宽度，包括padding、border、scrollbars）
  swiperTotalWidth = swiper.offsetWidth;
  // 获取元素当前样式 CSS2Properties(0) 样式表
  swiperStyle = swiper.style;
  indecatorItems = document.getElementsByClassName("indicator-item");
  
}

let setTransform = (position) => {
  swiperStyle.transform = `translate3d(${position}px, 0px, 0px)`;
}

let startTimer = () => {
  swiperTimer = window.setInterval(() => {
    currentIndex++;
    let position = -currentIndex * swiperTotalWidth;
    swiperStyle.transition = 'transform 300ms'; // 动画执行0.3秒
    setTransform(position);
    correctingPosition();
  }, 3000)
}

function showCurrentDot() {
  for (var i = 0, len = indecatorItems.length; i < len; i++) {
    indecatorItems[i].className = "indicator-item";
  }
  let index = currentIndex - 1;
  indecatorItems[index].className = "indicator-item indicator-item-active";
}

let correctingPosition = () => {
  window.setTimeout(() => {
    swiperStyle.transition = '0ms'; // 清除动画
    
    if (currentIndex == (swiperItemCount + 1)) {
      currentIndex = 1;
      setTransform(-currentIndex * swiperTotalWidth);
    } else if (currentIndex == 0) {
      currentIndex = swiperItemCount;
      setTransform(-currentIndex * swiperTotalWidth);
    }
    showCurrentDot();
  }, 300);
}

let scrollContent = (currentPosition) => {
  // 1.开始滚动动画
  // transform 300ms
  swiperStyle.transition = 'transform 300ms';
  setTransform(currentPosition);
  // 2.判断滚动到的位置
  correctingPosition();

}

let preAction = () => {
  // 停止定时器
  window.clearInterval(swiperTimer);
  // 2.修改index和位置
  currentIndex -= 1;
  scrollContent(-currentIndex * swiperTotalWidth);
  startTimer();
}

let nextAction = () => {
  // 停止定时器
  window.clearInterval(swiperTimer);
  // 2.修改index和位置
  currentIndex += 1;
  scrollContent(-currentIndex * swiperTotalWidth);
  startTimer();
}

let touchmoveEvent = (e) => {
  console.log("onmouseover");
}